#include <math.h>    //MST_MCU
#include "types.h"
#include "board.h"
#include "keypaddef.h"
#include "ms_reg.h"
#include "global.h"
#include "debug.h"
#include "Common.h"
#include "misc.h"
#include "ms_rwreg.h"
#include "mcu.h"
#include "menudef.h"
#include "gpio_def.h"
#if USEFLASH
#include "userpref.h"
#endif

BYTE xdata KeyDebug=0;
BYTE xdata LastKeypadButton=0;

extern void Osd_Hide( void );
extern void SaveMonitorSetting( void );
extern Bool ResetAllSetting( void );
extern Bool PowerOffSystem( void );
extern Bool ExecuteKeyEvent( MenuItemActionType menuAction );

#if ENABLE_MHL_CTS_TEST
extern void mapi_mhl_CbusSendCommand(BYTE ucSelect);
#endif

//================================================================
extern BYTE xdata MenuPageIndex;
extern BYTE xdata MenuItemIndex;
//2006-07-10

BYTE Key_GetKeypadStatus( void )
{
    BYTE temp, temp1, retry_Key;
    BYTE keypad = 0xFF;
    if ( KeyDebug )
    {
#if 0//DEBUG_EN
        printData("@@@@ Key:%x", KeyDebug);
#endif
        LastKeypadButton = KeyDebug;
        keypad &= (~KeyDebug);
        KeyDebug = 0;
        return keypad;
    }
    else
    {
    retry_Key = 3;
    while( retry_Key )
    {
        temp = KEYPAD_ADC_A;
        Delay1ms( 2 );
        temp1 = KEYPAD_ADC_A;
        if( abs( temp - temp1 ) < 3 )
            break;
        retry_Key--;
    }

#if MainBoardType == MainBoard_MST135B || MainBoardType == MainBoard_MST125B || MainBoardType == MainBoard_MST144A_A02A \
    || MainBoardType == MainBoard_TSUML887DC5 || MainBoardType == MainBoard_TSUMP387MT9_1_DP \
    || MainBoardType == MainBoard_TSUMP387MT9_1 || MainBoardType == MainBoard_tsuml88bdc2_1 \
    || MainBoardType == MainBoard_TSUML88CMC2 || MainBoardType == MainBoard_TSUML18CN2 || MainBoardType == MainBoard_TSUML887DS_1\
    || MainBoardType == MainBoard_TSUML58CN3 || (MainBoardType == MainBoard_TSUMOP38CMT9_HHD) || (MainBoardType == MainBoard_TSUMOP38CMT9_HDH)\
    || MainBoardType == MainBoard_TSUMO58CMG_H || MainBoardType == MainBoard_TSUMO58CMG_DP \
    || MainBoardType == MainBoard_TSUMP589MG_DP || MainBoardType == MainBoard_TSUMU589MT9_H || MainBoardType == MainBoard_TSUMP589HT9_DP\
    ||(MainBoardType == MainBoard_TSUMP589MG_H)||(MainBoardType == MainBoard_TSUMO58FMG_H_) || (MainBoardType == MainBoard_MST125A_A01B_S)  || (MainBoardType == MainBoard_MST250B_D01A_S)
    if(temp < 0x20) // 0
        keypad &= ~KEY_MINUS;
    else if(temp < 0xf0) // 0x48
        keypad &= ~KEY_MENU;
	else
		keypad &= ~KEY_RELEASE; //wz 2017.08.01 key release
#elif (MainBoardType == MainBoard_MST139A)
    if(temp < 0x20) // 0
        keypad &= ~KEY_MINUS;
    else if(temp < 0xf0) // 0x48
        keypad &= ~KEY_EXIT;
#elif MainBoardType == MainBoard_5270_M0A//||MainBoardType ==MainBoard_5281_M0A
    if(temp < 0x60) // 0
        keypad &= ~KEY_EXIT;
    else if(temp < 0xf0) // 0x48
        keypad &= ~KEY_PLUS;
#elif MainBoardType == MainBoard_5281_M0A   // Annie 2011.10.9
#if 1
    // 20111014.  Gary.Wang. follow KL 1013 comment
    if(temp < 0x60) // 0
        keypad &= ~KEY_EXIT;
    else if(temp < 0xf0) // 0x48
        keypad &= ~KEY_PLUS;
    #else //For FQ test only
    if(temp < 0x10) // 0
        keypad &= ~KEY_PLUS;
    else if(temp < 0x60) // 0x57
        keypad &= ~KEY_EXIT;
#endif
#elif MainBoardType == MainBoard_5269_M0A
    if(temp < 0x45) // 0x34
        keypad &= ~KEY_MENU;
    else if(temp < 0xf0) // 0x56
        keypad &= ~KEY_MINUS;
#elif MainBoardType == MainBoard_3834_M02   //111017 Annir follow EE change keypad
    if(temp < 0x7A) // 0
        keypad &= ~KEY_EXIT;
    else if(temp < 0x90) // 0x48
        keypad &= ~KEY_PLUS;
#else
#message "KEYPAD_ADC_A not coding"
#endif


#if ADC_KEY_PRESS_DEBUG_ENABLE
    if( temp < 0xfa )
        printData( "KEYPAD_ADC_A=0x%x", temp );
#endif

    retry_Key = 3;
    while( retry_Key )
    {
        temp = KEYPAD_ADC_B;
        Delay1ms( 2 );
        temp1 = KEYPAD_ADC_B;
        if( abs( temp - temp1 ) < 3 )
            break;
        retry_Key--;
    }

#if MainBoardType == MainBoard_MST135B || MainBoardType == MainBoard_MST125B||MainBoardType == MainBoard_MST144A_A02A \
    || MainBoardType == MainBoard_TSUML887DC5 || MainBoardType == MainBoard_TSUMP387MT9_1_DP \
    || MainBoardType == MainBoard_TSUMP387MT9_1 || MainBoardType == MainBoard_tsuml88bdc2_1 \
    || MainBoardType == MainBoard_TSUML88CMC2 || MainBoardType == MainBoard_TSUML18CN2 || MainBoardType == MainBoard_TSUML887DS_1\
    || MainBoardType == MainBoard_TSUML58CN3 || (MainBoardType == MainBoard_TSUMOP38CMT9_HHD) || (MainBoardType == MainBoard_TSUMOP38CMT9_HDH)\
    || MainBoardType == MainBoard_TSUMO58CMG_H || MainBoardType == MainBoard_TSUMO58CMG_DP \
    || MainBoardType == MainBoard_TSUMP589MG_DP || MainBoardType == MainBoard_TSUMU589MT9_H || MainBoardType == MainBoard_TSUMP589HT9_DP\
    ||(MainBoardType == MainBoard_TSUMP589MG_H)||(MainBoardType == MainBoard_TSUMO58FMG_H_) || (MainBoardType == MainBoard_MST125A_A01B_S) ||(MainBoardType == MainBoard_MST250B_D01A_S)
    if(temp < 0x20) // 0
        keypad &= ~KEY_PLUS;
    else if(temp < 0x70) // 0x48
        keypad &= ~KEY_EXIT;
	else
		keypad &= ~KEY_RELEASE; //wz 2017.08.01 key release
#elif (MainBoardType == MainBoard_MST139A)
    if(temp < 0x20) // 0
        keypad &= ~KEY_PLUS;
    else if(temp < 0x70) // 0x48
        keypad &= ~KEY_MENU;
#elif MainBoardType == MainBoard_5270_M0A//||MainBoardType ==MainBoard_5281_M0A
    if(temp < 0x60) // 0
        keypad &= ~KEY_MENU;
    else if(temp < 0xf0) // 0x48
        keypad &= ~KEY_MINUS;
#elif MainBoardType == MainBoard_5281_M0A   // Annie 2011.10.9
#if 1
    // 20111014.  Gary.Wang. follow KL 1013 comment
    if(temp < 0x60) // 0
        keypad &= ~KEY_MENU;
    else if(temp < 0xf0) // 0x48
        keypad &= ~KEY_MINUS;
    #else   //For FQ test only
    if(temp < 0x40) // 0x33
        keypad &= ~KEY_MENU;
    else if(temp < 0x60) // 0x57
        keypad &= ~KEY_MINUS;
#endif
#elif MainBoardType == MainBoard_5269_M0A
    if(temp < 0x30) // 0
        keypad &= ~KEY_PLUS;
    else if(temp < 0xf0) // 0x56
        keypad &= ~KEY_EXIT;
#elif MainBoardType == MainBoard_3834_M02   //111017 Annir follow EE change keypad
    if(temp < 0x7A) // 0
        keypad &= ~KEY_MENU;
    else if(temp < 0x90) // 0x48
        keypad &= ~KEY_MINUS;
#else
#message "KEYPAD_ADC_B not coding"
#endif


#if ADC_KEY_PRESS_DEBUG_ENABLE
    if( temp < 0xfa )
        printData( "KEYPAD_ADC_B=0x%x", temp );
#endif
#if ADC_KEY_PRESS_DEBUG_ENABLE
        printData( "PowerKey=0x%x", PowerKey );
#endif

    if(PowerKey == 0 )
    {
        keypad &= ~KEY_POWER;
    }
    return keypad;
}
}
void CheckFactoryKeyStatus( void )
{
    BYTE keypadStatus;
    keypadStatus = ( Key_GetKeypadStatus() ^ KeypadMask ) &KeypadMask;
    Clr_FactoryModeFlag();

    if( keypadStatus == KEY_MENU )
    {
        Set_FactoryModeFlag();
        Set_PowerOnFlag();
    }
}
void Key_ScanKeypad( void )
{
#if ENABLE_TOUCH_KEY
    WORD keypadStatus;
#else
    BYTE keypadStatus;
#endif

    if( gBoolVisualKey == 0 )
    {
#if ENABLE_TOUCH_KEY
        keypadStatus = ( TouchKey_GetKeyStatus() ^ KeypadMask ) &KeypadMask;
        Set_bKeyReadyFlag();
#else
        keypadStatus = ( Key_GetKeypadStatus() ^ KeypadMask ) &KeypadMask;
        Set_bKeyReadyFlag();
#endif

    }
    else if( gBoolVisualKey == 1 )
    {
        gBoolVisualKey = 0;
        keypadStatus = ( gByteVisualKey ^ KeypadMask ) &KeypadMask;
    }

    if( !bKeyReadyFlag )
    {
        return;
    }

#if ENABLE_MHL_CTS_TEST
        //if(KeypadButton <= BTN_Exit)
        {
            mapi_mhl_CbusSendCommand(CBUS_COMMAND_RCP);
        }
#endif

	#if ZORO_ENABLE_DEBUG
		printData("keypadStatus = %x", keypadStatus);
		printData("LastKeypadButton = %x", LastKeypadButton);
	#endif

    if( keypadStatus )
    {
    	/*wz 2017.08.01 zoro start
    	 *when the combo key is released ,we set the flag of keyComboFlag.
    	 *The flag is be used for displaymode change
    	 */
    	if((LastKeypadButton == KEY_COMBO) && (keypadStatus == KEY_RELEASE))
    	{
    		printMsg("KEY_COMBO <-> KEY_RELEASE!");
			Set_keyComboFlag();
		}
		/*wz 2017.08.01 zoro end*/
		
        if (LastKeypadButton!=keypadStatus)
        {
            LastKeypadButton=keypadStatus;
            KeypadButton=BTN_Nothing;
            goto KeyEnd;
        }
		/*wz 2017.08.01 zoro start
		 *ignore KEY_COMBO and KEY_RELEASE,
		 *this is only be used for displaymode change
		 */
		if(( keypadStatus == KEY_COMBO ) || ( keypadStatus == KEY_RELEASE )) 
		{
			KeypadButton=BTN_Nothing;
        	goto KeyEnd;
		}
		/*wz 2017.08.01 zoro end*/

		if(keypadStatus & (~KEY_RELEASE)) //the key is press
		{
			keypadStatus &= (~KEY_RELEASE); //ignore the release key
		}
		
        /*if( keypadStatus == KEY_PRODUCT && ProductModeFlag )
        {
            if( MenuPageIndex == RootMenu ||
                    MenuPageIndex == HotKeyECOMenu
#if AudioFunc
                    || MenuPageIndex == HotKeyVolMenu
#endif
              )
            {
                Osd_Hide();
                ResetAllSetting();
            }
            else
                KeypadButton = BTN_Nothing;

            return;
        }*/
        if( KeypadButton == BTN_Repeat && keypadStatus != KEY_LOCK
#if 1//ENABLE_TOUCH_KEY  open by smc.LMW 20151118 for factoryMode
                && keypadStatus != KEY_FACTORY // 100524 coding addition for factory key
#endif
        )        // 0105
            return ;
        //0105
        {
#if 1
            if( keypadStatus == KEY_LOCK )
            {
                if( KeypadButton == BTN_Power || KeypadButton == BTN_LockRepeat )
                    KeypadButton = BTN_LockRepeat;
                else
                {
                    if( !PowerOnFlag && !( MonitorFlags & OsdLockModeFlag ) )
                    {
                        Set_OsdLockModeFlag();
                        //Set_PowerOnFlag();
                        Set_ShowOsdLockFlag();
                        KeypadButton = BTN_Power;
                    }
                    else if(( !PowerOnFlag ) && ( MonitorFlags & OsdLockModeFlag ) )
                    {
                        Clr_OsdLockModeFlag();
                        //Set_PowerOnFlag();
                        Clr_ShowOsdLockFlag();
                        KeypadButton = BTN_Power;
                    }
                }
                #if USEFLASH
                Set_FlashSaveMonitorFlag();
                #else
                SaveMonitorSetting();
                #endif
            }
#if 1 //ENABLE_TOUCH_KEY //Open By SMC.LMW 20151118 for factoryMode
            else if( keypadStatus == KEY_FACTORY ) // 100524 coding addition for factory key
            {
            	//printData("KEY_FACTORY Push OK!",NULL);
               // if( !PowerOnFlag )
                {
                //	printData("Set_FactoryModeFlag OK!",NULL);
                    Clr_OsdLockModeFlag();
                    Clr_ShowOsdLockFlag();
                    Set_FactoryModeFlag();
					#if 0
                    MenuPageIndex = PowerOnMenu; // 100908
                    MenuItemIndex = 0;
                    ExecuteKeyEvent( MIA_RedrawMenu );
					#endif
                    //            KeypadButton = BTN_Power;
                }
            }
#endif
            else
#endif
                if( keypadStatus == KEY_PLUS )
                {
                #if HotExpansion
                    if( (MenuPageIndex == RootMenu || MenuPageIndex == HotExpansionMenu) && ( KeypadButton == BTN_Plus || KeypadButton == BTN_Repeat ) )
                        KeypadButton = BTN_Repeat;
                #elif 0//(AudioFunc && (ENABLE_HDMI || ENABLE_DP_INPUT))
                    if( (MenuPageIndex == RootMenu || (MenuPageIndex == HotKeySourceVolMenu && MenuItemIndex == 0)) && ( KeypadButton == BTN_Plus || KeypadButton == BTN_Repeat ) )
                        KeypadButton = BTN_Repeat;
                #else
                    if( (MenuPageIndex == RootMenu) && ( KeypadButton == BTN_Plus || KeypadButton == BTN_Repeat ) )
                        KeypadButton = BTN_Repeat;
                #endif
                    else
                    {
                        KeypadButton = BTN_Plus;
                    }
                }
                else if( keypadStatus == KEY_MINUS )
                {
                    if( (MenuPageIndex == RootMenu || MenuPageIndex == HotKeyECOMenu) && ( KeypadButton == BTN_Minus || KeypadButton == BTN_Repeat ) )
                        KeypadButton = BTN_Repeat;
                    else
                        KeypadButton = BTN_Minus;
                }
                else if( keypadStatus == KEY_MENU )
                {
                    if( KeypadButton == BTN_Menu || KeypadButton == BTN_Repeat )
                        KeypadButton = BTN_Repeat;
                    else
                    {
                        KeypadButton = BTN_Menu;
                    }
                }
                else if( keypadStatus == KEY_EXIT )
                {
                    if( KeypadButton == BTN_Exit || KeypadButton == BTN_Repeat )
                        KeypadButton = BTN_Repeat;
                    else
                    {
#if HotInputSelect
#ifndef SixKeyAutoDirectAndSourceSelect
                        if( MenuPageIndex == RootMenu || MenuPageIndex == UnsupportedModeMenu )
                        {
                            if( !PressExitFlag )
                            {
                                Set_PressExitFlag();
                                HotKeyCounter = 2;
                            }
                            KeypadButton = BTN_Nothing;
                        }
                        else
#endif
#endif
                        {
                            KeypadButton = BTN_Exit;
                        }
                    }
                }
                else if( keypadStatus == KEY_SELECT )
                    //2006-02-22
                {
                    if( KeypadButton == BTN_Repeat )
                        KeypadButton = BTN_Repeat;
                    else
                    {
                        KeypadButton = BTN_Select;
                    }
                }
                else if( keypadStatus == KEY_POWER )
                {
#if ENABLE_TOUCH_KEY
#if TOUCH_KEY_POWER_KEY_DEBOUNCE
                    bPowerKeyPressed = 1;
                    if( PowerKeyDebounceCntr >= POWER_KEY_DEBOUNCE_PEROID )
                    {
                        if( KeypadButton == BTN_Power || KeypadButton == BTN_Repeat )
                            KeypadButton = BTN_Repeat;
                        else
                            KeypadButton = BTN_Power;
                    }
                    else
                    {
                        KeypadButton = BTN_Nothing;
                    }
#else
                    if( KeypadButton == BTN_Power || KeypadButton == BTN_Repeat )
                        KeypadButton = BTN_Repeat;
                    else
                        KeypadButton = BTN_Power;
#endif
#else
                    if( KeypadButton == BTN_Power || KeypadButton == BTN_Repeat )
                        KeypadButton = BTN_Repeat;
                    else
                        KeypadButton = BTN_Power;
#endif

                }
                else
                {
#if ENABLE_TOUCH_KEY
#if TOUCH_KEY_POWER_KEY_DEBOUNCE
                    bPowerKeyPressed = 0;
                    PowerKeyDebounceCntr = 0;
#endif
#endif

                    KeypadButton = BTN_Nothing;
                }
        }

#if 0//ENABLE_MHL_CTS_TEST
        //if(KeypadButton <= BTN_Exit)
        {
            mapi_mhl_CbusSendCommand(CBUS_COMMAND_RCP);
        }
#endif

    }
    else
    {
#if HotInputSelect
        if( PressExitFlag )
        {
            if( MenuPageIndex == RootMenu || MenuPageIndex == UnsupportedModeMenu )
            {
                KeypadButton = BTN_Select;
                HotKeyCounter = 0;
                Clr_EnableShowAutoFlag();
            }
            if( SyncLossState() )
                Clr_PressExitFlag();
        }
#endif
        KeypadButton = BTN_Nothing;
    LastKeypadButton=keypadStatus;
#if ENABLE_TOUCH_KEY
#if TOUCH_KEY_POWER_KEY_DEBOUNCE
        bPowerKeyPressed = 0;
        PowerKeyDebounceCntr = 0;
#endif
#endif

    }
    KeyEnd:
    KeyDebug = 0;
}
//================================================================
